/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\SystemSettings\StatementOfAccountConfig\ReconciliationLetterTemplate\index.tsx
 * @Date: 2022-03-16 16:38:17
 * @LastEditTime: 2022-04-06 15:01:05
 */
import UdSelect from '@/components/UdFormControls/UdSelect'
import { columnRenders, http, IUdColumn, UdFilter, UdModal, UdModalForm, UdTable, UdToolbar, validators } from '@/lib'
import { Button, Cascader, Input, message, Modal, Select, Tooltip } from 'antd'
import TextArea from 'antd/lib/input/TextArea'
import React, { Component } from 'react'
import CascaderOptions from '../components/CascaderOptions'
import apis from '@/apis/StatementOfAccount'
const { Option } = Select
type Props = {
  brandList: ReadonlyArray<any>
}

type State = {
  conditions: any[]
  loading: boolean
  page: number
  size: number
  total: number
  dataSource: any[]
}

type R_Params = {
  brandCode: string
  modelName: string
  title: string
  rise: string
  address: string
  detailedAddress: string
  contacts: string
  phone: string
  economicBusinessIds: string
  other: string
  conclusionOn: string
  conclusionTw: string
}

export default class EconomicBusinessConfig extends Component<Props, State> {
  private filterForm: any
  private brandList: ReadonlyArray<any> = this.props.brandList
  private labelCol: any = { span: 4 }
  state: State = {
    conditions: [
      {
        label: '品牌公司',
        id: 'brandCode',
        initialValue: this.brandList[0].value,
        render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
      },
    ],
    page: 1,
    size: 10,
    total: 0,
    loading: false,
    dataSource: [],
  }
  columns: IUdColumn<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    {
      title: '模板名称',
      dataIndex: 'modelName',
      align: 'center',
      key: 'modelName',
      width: '230',
      render: (text, record) => {
        return (
          <Tooltip title={record.modelName}>
            <div style={{ width: '100%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.modelName}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: '160px',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right' as 'right',
      width: 130,
      render: columnRenders.operate([
        {
          title: '编辑',
          action: (text: any, record: any) => {
            this.handerDrawer(record)
          },
        },
        {
          title: '预览',
          action: (text: any, record: any) => {
            this.handPreview(record)
          },
        },
        {
          title: '删除',
          action: (text: any, record: any) => {
            Modal.confirm({
              title: '删除',
              content: `确定删除【${record.modelName}】此模板吗`,
              okType: 'danger',
              onOk: () => {
                return this.handDeleteReconciliation(record.id)
              },
            })
          },
        },
      ]),
    },
  ]

  componentDidMount(): void {
    this.getRecordTableData()
  }

  private handDeleteReconciliation = (id: number) => {
    return http
      .get(apis.deleteReconciliation, { params: { id } })
      .then(() => {
        message.success('删除成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handleSearch = (values: any) => {
    this.setState({ page: 1 }, () => {
      this.getRecordTableData()
    })
  }
  private resetFilterHandle = form => {
    this.setState(
      {
        dataSource: [],
        page: 1,
        total: 0,
      },
      () => {
        this.getRecordTableData()
      }
    )
  }

  private handAddReconciliation = (params: R_Params) => {
    return http
      .post(apis.addReconciliation, params)
      .then(() => {
        message.success('添加成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handUpdateReconciliation = (params: R_Params) => {
    return http
      .post(apis.updateReconciliation, params)
      .then(() => {
        message.success('编辑成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handPreview = (record: object) => {
    const rex = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
    if (rex.test(record['modelUrl'])) {
      UdModal.open({
        title: record['modelName'],
        width: '80%',
        bodyStyle: { padding: '0' },
        centered: true,
        content: (
          <div style={{ height: '700px', overflow: 'hidden' }}>
            <iframe
              title={record['modelName']}
              src={`https://view.officeapps.live.com/op/view.aspx?src=${record['modelUrl']}`}
              width="100%"
              height="100%"
              frameBorder="0"
              style={{ border: 'none' }}
              seamless
            ></iframe>
          </div>
        ),
        footer: null,
      })
    } else {
      message.error('附件URL无效')
    }
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }
  private getRecordTableData = async () => {
    this.setState({ loading: true })
    try {
      let list: any = await http.post(apis.getReconciliationList, {
        page: this.state.page,
        size: this.state.size,
        conditions: this.filterForm.getFieldsValue(),
      })
      const dataSource = list.data?.content
      this.setState({
        dataSource,
        total: list.data.totalElements,
        loading: false,
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }

  private getEconomicBusinessList = async () => {
    let list: any = await http.post(apis.getEconomicBusinessList, {
      page: 1,
      size: 9999,
      conditions: this.filterForm.getFieldsValue(),
    })
    const dataSource = list.data?.content || []
    return dataSource
  }

  private handerDrawer = async (record?) => {
    const list = await this.getEconomicBusinessList()
    let Options = list.map(item => (
      <Option value={item.id + ''} key={item.id}>
        {item.projectName}
      </Option>
    ))
    let values = record
      ? { ...record }
      : {
          rise: '首先感谢贵公司长期以来对我公司的支持。按照我公司内部管理的要求，应当每季度作本公司与贵公司的往来账项等事项核对。下列信息出自本公司账簿记录，如与贵公司记录相符，请在本函下端“信息证明无误”处签章证明；如有不符，请在“信息不符”处列明不符项目；如存在与本公司有关的未列入本函的其他项目，也请在“信息不符”处列出这些项目的金额及详细资料。回函请直接寄至以下地址。',
          other: '并非催款结算。若款项在上述日期之后已经付清，仍请及时函复为盼。',
          conclusionOn: '信息证明无误。',
          conclusionTw: '信息不符，请列明不符项目及具体内容',
        }

    values && (values.address = values?.address?.split(','))
    values && (values.economicBusinessIds = values?.economicBusinessIds?.split(','))
    UdModal.open({
      title: record ? '编辑' : '新增',
      width: '45%',
      content: (
        <UdModalForm
          values={values}
          labelCol={this.labelCol}
          items={[
            { id: 'modelName', label: '模板名称', rules: [validators.required] },
            {
              id: 'title',
              label: '标题',
              rules: [validators.required],
              render: <TextArea rows={2} maxLength={100} />,
            },
            {
              id: 'rise',
              label: '抬头信息',
              rules: [validators.required],
              render: <TextArea rows={3} maxLength={300} />,
            },
            {
              id: 'address',
              label: '回函地址',
              rules: [validators.required],
              render: <Cascader options={CascaderOptions} />,
            },
            {
              id: 'detailedAddress',
              label: '详细地址',
              rules: [validators.required],
              render: <TextArea rows={2} maxLength={100} />,
            },
            { id: 'contacts', label: '联系人', rules: [validators.required] },
            { id: 'phone', label: '联系电话', rules: [validators.required] },
            {
              id: 'economicBusinessIds',
              label: '经济业务项',
              rules: [validators.required],
              render: (
                <Select mode="multiple" showSearch optionFilterProp="children">
                  {Options}
                </Select>
              ),
            },
            {
              id: 'other',
              label: '其他事项',
              rules: [validators.required],
              render: <TextArea rows={2} maxLength={200} />,
            },
            {
              id: 'conclusionOn',
              label: '结论1',
              rules: [validators.required, validators.max(200)],
              render: <Input disabled={true} />,
            },
            {
              id: 'conclusionTw',
              label: '结论2',
              rules: [validators.required, validators.max(200)],
              render: <Input disabled={true} />,
            },
          ]}
        />
      ),
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        if (!record) {
          let params = { ...values }
          params.brandCode = this.filterForm.getFieldsValue()['brandCode']
          params.address = params.address.join(',')
          params.economicBusinessIds = params.economicBusinessIds.join(',')
          return this.handAddReconciliation(params)
        } else {
          let params = { ...record, ...values }
          params.address = params.address.join(',')
          params.economicBusinessIds = params.economicBusinessIds.join(',')
          return this.handUpdateReconciliation(params)
        }
      },
    })
  }
  render() {
    const { loading, page, size, total, dataSource, conditions } = this.state
    return (
      <>
        <UdFilter
          items={conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          getForm={form => {
            this.filterForm = form
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button
              type="primary"
              onClick={() => {
                this.handerDrawer()
              }}
            >
              新增
            </Button>
          }
        ></UdToolbar>
        <UdTable
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={dataSource}
          onChange={this.handleChangePage}
          scroll={{ x: true }}
          pagination={{
            current: page,
            pageSize: size,
            total: total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </>
    )
  }
}
